package com.resign.carl.composite.api.impl;

import com.resign.carl.composite.api.MenuComponent;

import java.util.Iterator;
import java.util.Stack;

/**
 * Created by carl.zhao on 2016/6/16.
 */
public class CompositeIterator implements Iterator<MenuComponent> {

    Stack<Iterator> stack = new Stack<Iterator>();

    public CompositeIterator(Iterator<MenuComponent> iterator){
        stack.push(iterator);
    }

    @Override
    public boolean hasNext() {
        if(stack.empty()){
            return false;
        } else {
            Iterator iterator = stack.peek();
            if(!iterator.hasNext()){
                stack.pop();
                return hasNext();
            } else {
                return true;
            }
        }
    }

    @Override
    public MenuComponent next() {
        if(hasNext()){
            Iterator<MenuComponent> iterator = stack.peek();
            MenuComponent component = iterator.next();
            if(component instanceof Menu){
                Menu menu = (Menu) component;
                stack.push(menu.createIterator());
            }
        }
        return null;
    }

    @Override
    public void remove() {
        throw new UnsupportedOperationException();
    }
}
